<?php
/**
  * wechat php test
  */

//define your token
define("TOKEN", "liuxiang");
$wechatObj = new wechatCallbackapiTest();
// $wechatObj->valid();
$wechatObj->responseMsg();

class wechatCallbackapiTest
{
	public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
        	echo $echoStr;
        	exit;
        }
    }

    public function responseMsg()
    {
		//get post data, May be due to the different environments
        //$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
		$postStr = file_get_contents("php://input");
        //file_put_contents('test.txt', $postStr);
      	//extract post data
		if (!empty($postStr)){
                /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
                   the best way is to check the validity of xml by yourself */
                libxml_disable_entity_loader(true);
              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;  
                $MsgType = $postObj->MsgType; 
                //file_put_contents('test.txt', $MsgType,FILE_APPEND);
                    switch ($MsgType) {
                        case 'text':
                            $keyword = trim($postObj->Content);
                            $this->sendText($toUsername, $fromUsername,$keyword);
                        break;
                        case 'image':
                            $this->sendImage($toUsername, $fromUsername);
                        break;
                        case 'voice':
                            $contentStr = "我是语音!";
                        break;
                        case 'video':
                            $this->sendVideo($toUsername, $fromUsername);
                        break;
                        case 'location':
                            $contentStr = "我是定位!";
                            $this->sendText($toUsername, $fromUsername,'location',$postObj->Location_Y.",".$postObj->Location_X);
                        break;
                        case 'link':
                            $contentStr = "我是链接!";
                        break;
                        case 'event':
                            $event = trim($postObj->Event);
                            $this->sendText($toUsername, $fromUsername,$event,$postObj->EventKey);
                        break;
                        default:
                            $contentStr = "我是".$oldType."!";
                        break;
                    }
        }else {
        	echo "";
        	exit;
        }
    }
	
    public function sendText($fromUsername, $toUsername,$keyword='',$str=''){

        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>0</FuncFlag>
                    </xml>"; 
        switch ($keyword) {
            case '你好':
                $contentStr = "666!";
            break;
            
            case '社会':
                $contentStr = "777!";
            break;

            case '图文':
                $this->sendNews($fromUsername, $toUsername);
                return ;
            break;

            case '音乐':
                $this->sendMusic($fromUsername, $toUsername);
                return ;
            break;
            case 'subscribe':
                $contentStr = "欢迎！";
            break;
            case 'SCAN':
                $contentStr = $str;
            break;
            case 'location':
                //$contentStr = $str;
                $contentStr = "<a href='https://restapi.amap.com/v3/place/around?key=7b335c794cecde8750975da37318d3ac&location=".$str."&keywords='".urlencode('肯德基').">周边KFC</a>";
            break;
            default:
                $contentStr = "我是文本!";
            break;
        }
        $resultStr = sprintf($textTpl, $toUsername, $fromUsername, time(), 'text', $contentStr);
        echo $resultStr;

    }

    public function sendImage($fromUsername, $toUsername){
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[image]]></MsgType>
                    <Image>
                        <MediaId><![CDATA[%s]]></MediaId>
                    </Image>
                    </xml>";
        $MediaId = "4lZn9IDvbzL8ESwYAD8oa0dTeerZJcZFNSJItyG15x7hm-k3n5jFbDvuRXRS_l4e";
        $resultStr = sprintf($textTpl, $toUsername, $fromUsername, time(), $MediaId);
        echo $resultStr;
    }

    public function sendVideo($fromUsername, $toUsername){

        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[video]]></MsgType>
                    <Video>
                        <MediaId><![CDATA[%s]]></MediaId>
                        <Title><![CDATA[%s]]></Title>
                        <Description><![CDATA[%s]]></Description>
                    </Video> 
                    </xml>";

        $MediaId = "3WRSWCcxmjeJgh9yG7iCi4xkQGbcQRszXmw5woSdpzGwFuihj6mD-iAyoP15QrYp";
        $title = "视频";
        $desc = "描述";
        $resultStr = sprintf($textTpl, $toUsername, $fromUsername, time(), $MediaId,$title,$desc);
        echo $resultStr;
    }

    public function sendMusic($fromUsername, $toUsername){
        $textTpl = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[music]]></MsgType>
        <Music>
            <Title><![CDATA[%s]]></Title>
            <Description><![CDATA[%s]]></Description>
            <MusicUrl><![CDATA[%s]]></MusicUrl>
            <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
            <ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
        </Music>
        </xml>";
        $title = "不能说的秘密";
        $desc = "不能说的秘密--周杰伦";
        $musicurl = "http://lx.medequle.xyz/bnsdmm.mp3";
        $hq = "http://lx.medequle.xyz/bnsdmm.mp3";
        $thumb = "eyUkl5dUYwGVxFHVrMF4Bl9xGbZTmTW9ugvwkOuqTqKrRzQ6URs46HzlqzTJ741Y";
        echo $resultStr = sprintf($textTpl, $toUsername, $fromUsername, time(),$title,$desc,$musicurl,$hq,$thumb);
    }

    public function sendNews($fromUsername, $toUsername){
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[news]]></MsgType>
                    <ArticleCount>1</ArticleCount>
                    <Articles>
                        <item>
                            <Title><![CDATA[%s]]></Title> 
                            <Description><![CDATA[%s]]></Description>
                            <PicUrl><![CDATA[%s]]></PicUrl>
                            <Url><![CDATA[%s]]></Url>
                        </item>
                    </Articles>
                    </xml>";
        $title = "图文";
        $desc = "描述";
        $pic = "http://lx.medequle.xyz/1.jpg";
        $url = "http://lx.medequle.xyz";
        echo $resultStr = sprintf($textTpl, $toUsername, $fromUsername, time(), $title,$desc,$pic,$url);
    }

	private function checkSignature()
	{
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }
        
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        		
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
}

?>